package com.sy.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.UserService;
import com.sy.constant.JwtClaimsConstant;
import com.sy.dto.UserLoginDTO;
import com.sy.dto.UserRegisterDTO;
import com.sy.pojo.User;
import com.sy.properties.JwtProperties;
import com.sy.result.Result;
import com.sy.utils.JwtUtil;
import com.sy.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户端-用户相关接口
 */
@Api(tags = "用户端-用户相关接口")
@RestController("commonUserController")
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("查询用户名是否存在")
    @GetMapping("/doExistUsername")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "username", value = "要验证的用户名", required = true,dataTypeClass = String.class)
    )
    public Result<String> doExistUsername(String username) {
        log.info("用户名为：{}", username);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            return Result.success();
        } else {
            return Result.error("用户名已存在");
        }
    }

    @ApiOperation("查询手机号是否存在")
    @GetMapping("/doExistPhone")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "phone", value = "要验证的手机号", required = true,dataTypeClass = String.class)
    )
    public Result<String> doExistPhone(String phone) {
        log.info("手机号为：{}", phone);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            return Result.success();
        } else {
            return Result.error("手机号已存在");
        }
    }

    @ApiOperation("用户端注册")
    @PostMapping("/save")
    public Result save(@RequestBody UserRegisterDTO userRegisterDTO){
        try {
            log.info("注册用户：{}", userRegisterDTO);
            User user = new User();
            BeanUtils.copyProperties(userRegisterDTO, user);
            // 设置默认密码
            user.setPassword(DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes()));
            // 设置创建时间
            user.setCreatetime(LocalDateTime.now());
            userService.save(user);
        } catch (BeansException e) {
            throw new RuntimeException("注册失败");
        }
        return Result.success("注册成功");
    }

    @ApiOperation("用户端登录")
    @PostMapping("login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("登录请求：{}" + userLoginDTO);
        User user = userService.login(userLoginDTO);
        //把当前登录用户的id，存入map,再将map放入token（jwt生成）中
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUid());
        // 生成token
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //把user对象中的数据复制到UserLoginVO
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);
        return Result.success(userLoginVO);
    }
}
